package com.ycl.javacore.algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/10
 * Time: 9:01 PM
 * Desc: 反转二叉树
 */
public class AlgoCast47 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 利用递归 翻转二叉树
     *
     * @param root
     * @return
     */
    public TreeNode invertBinaryTreeByRecursive(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        invertBinaryTreeByRecursive(root.left);
        invertBinaryTreeByRecursive(root.right);
        return root;
    }

    /**
     * 按照树的深度，层层遍历
     * @param root
     * @return
     */
    public TreeNode invertBinaryTreeByIterative(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;

            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
        }
        return root;
    }

}
